//
//  AUExtension_Color.swift
//  AwesomeUBaseModule_Example
//
//  Created by Miss_Special on 2018/4/13.
//  Copyright © 2018 CocoaPods. All rights reserved.
//

// MARK:- Convenience
public extension UIColor {
    
    /// 根据r, g, b, a创建颜色
    convenience init(au_rgbColor r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1.0) {
        self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a)
    }
    
    /// 根据hexString创建颜色
    convenience init(au_hexString hexString: String, alpha: CGFloat = 1.0) {
        
        let scanner = Scanner(string: hexString)
        scanner.scanLocation = hexString.hasPrefix("#") ? 1 : 0
        
        var rgbValue: UInt64 = 0
        
        scanner.scanHexInt64(&rgbValue)
        
        let r = (rgbValue & 0xff0000) >> 16
        let g = (rgbValue & 0xff00) >> 8
        let b = rgbValue & 0xff
        
        self.init(red: CGFloat(r) / 0xff, green: CGFloat(g) / 0xff, blue: CGFloat(b) / 0xff, alpha: alpha > 1 ? 1.0 : alpha)
    }
}

// MARK:- Property
public extension UIColor {
    /// 转hexString
    var au_toHexString: String {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        
        self.getRed(&r, green: &g, blue: &b, alpha: &a)
        
        return String(
            format: "#%02X%02X%02X",
            Int(r * 0xff),
            Int(g * 0xff),
            Int(b * 0xff)
        )
    }
}

// MARK:- Function
public extension UIColor {
    /// 获取随机颜色
    static func au_randomColor() -> UIColor {
        return UIColor(au_rgbColor: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))
    }
}
